import axios from '../../api/request'
import {AxiosResponse} from 'axios'
import {Component} from 'react'
import {Navigate} from 'react-router-dom'
import {Button, message} from 'antd';
import ReactECharts from 'echarts-for-react';
import moment from 'moment'
import './style.css'

interface State {
  isLogin: boolean,
  isLoaded: boolean,
  data: responseResult.DataStructure
}

class Home extends Component {
  state: State = {
    isLogin: false,
    isLoaded: false,
    data: {}
  }
  
  componentDidMount() {
    axios.get('/api/isLogin').then((res: AxiosResponse<responseResult.isLogin>) => {
      const data: responseResult.isLogin = res.data
      this.setState({
        isLogin: data,
        isLoaded: true
      })
      res.data && this.handleShow()
    })
  }
  
  componentWillUnmount() {
    this.setState = () => false
  }
  
  handleCrawler = () => {
    axios.get('/api/getData').then(() => {
      message.success('爬取成功')
      this.handleShow()
    })
  }
  
  handleShow = () => {
    axios.get('/api/showData').then((res: AxiosResponse<responseResult.showData>) => {
      if (res.code && res.code === 200) {
        const data: responseResult.showData = res.data
        this.setState({data})
      } else {
        message.error(res.msg)
      }
    })
  }
  
  handleLogout = () => {
    axios.get('/api/logout').then(() => {
      this.setState({
        isLogin: false
      })
    })
  }
  
  getOption: () => echarts.EChartsOption = () => {
    const {data} = this.state
    const legend: string[] = []
    const xAxis: string[] = []
    const tempData: {
      [key: string]: number[]
    } = {}
    for (let key in data) {
      xAxis.push(moment(Number(key)).format('MM-DD hh:mm'))
      const item = data[key]
      item.forEach(innerItem => {
        const {title, count} = innerItem
        if (!legend.includes(title)) {
          legend.push(title)
        }
        tempData[title] ? tempData[title].push(count) : tempData[title] = [count]
      })
    }
    const series: echarts.LineSeriesOption[] = []
    for (let i in tempData) {
      series.push({
        name: i,
        type: 'line',
        data: tempData[i]
      })
    }
    return {
      title: {
        text: '课程在线学习人数'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: legend
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxis
      },
      yAxis: {
        type: 'value'
      },
      series
    }
  }
  
  render() {
    if (this.state.isLoaded) {
      if (this.state.isLogin) {
        return (
          <div>
            <div className="home-page">
              <Button type="primary" onClick={this.handleCrawler}>爬取</Button>
              <Button danger type="primary"
                      onClick={this.handleLogout}>退出</Button>
            </div>
            <ReactECharts option={this.getOption()}/>
          </div>
        )
      } else {
        return <Navigate to="/login"/>
      }
    } else {
      return null
    }
  }
}

export default Home